<template id="carType">
  <div>
    <el-row style="height: 100%;border: 1px solid #DCDFE6;margin-top: 10px">
      <el-col :span="6" style="border-right: 1px solid #DCDFE6; min-height:500px;">
        <div class="grid-content bg-purple">
          <el-input
              placeholder="输入关键字进行过滤"
              v-model="filterText">
          </el-input>

          <el-tree :data="carTypes"
                   class="filter-tree"
                   :props="defaultProps"
                   :highlight-current="true"
                   :filter-node-method="filterNode"
                   @node-click="handleNodeClick"
                   ref="tree">
          </el-tree>
        </div>
      </el-col>
      <el-col :span="17" style="margin-left: 10px;padding-top: 10px">
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
          <el-form :inline="true" :model="filters">
            <el-form-item>
              <el-input v-model="filters.keyword" placeholder="关键字"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" v-on:click="getList(addForm.pid)">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" v-on:click="getTreeData">重置</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleAdd">新增</el-button>
            </el-form-item>
          </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="pageInfo.rows" highlight-current-row  @selection-change="selsChange" style="width: 100%;">
          <el-table-column type="selection" >
          </el-table-column>
          <el-table-column prop="name" label="标题" width="120" sortable>
          </el-table-column>
          <el-table-column prop="icon" label="LOGO" width="120" sortable>
            <template v-slot="scope">
              <img :src="imageUrl+''+scope.row.icon" alt="" style="width: 50px;height: 50px">
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" width="120" sortable>
          </el-table-column>
          <el-table-column prop="totalCount" label="课程数量" width="120" sortable>
          </el-table-column>

          <el-table-column label="操作" width="150">
            <template v-slot="scope">
              <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
          <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
          <el-pagination layout="total,sizes,prev, pager, next"
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page="query.currentPage"
                         :page-sizes="[5, 10, 50, 100]"
                         :page-size="10"
                         :total="pageInfo.total"
                         style="float:right;">
          </el-pagination>
        </el-col>

      </el-col>
    </el-row>

    <!--新增界面-->
    <el-dialog title="新增" :visible.sync="addFormVisible"  :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px"  ref="addForm">
        <el-form-item label="分类标题" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="LOGO" prop="logo">
<!--          <el-input v-model="addForm.logo" auto-complete="off"></el-input>-->
          <el-upload
              class="upload-demo"
              action="http://localhost:8085/fastDfs/upload"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="排序" prop="sortIndex">
          <el-input v-model="addForm.sortIndex" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="addForm.description" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" >提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.el-row {
  margin-bottom: 20px;
  height: 100%;
}
:last-child {
  margin-bottom: 0;
}
#carType el-col {
  border: 1px solid red;
  border-radius: 4px;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
</style>

<script>
export default {
  data() {
    return {
      imageUrl:this.imageUrl,
      headers:{
        token:localStorage.getItem("token")
      },
      filterText:"",
      currentID:null,
      // 分页查询
      pageInfo:{
        rows: [],
        total: 0,
      },
      // 查询体
      query:{
        id:'',
        currentPage:1,
        pageSize:10,
        keyword:null
      },
      addForm:{
        name:"",
        logo:"",
        icon:"",
        sortIndex:"",
        description:"",
        pid:""
      },
      addFormVisible:false,
      sels:[],
      filters:{
        keyword:""
      },
      datas:[],
      carTypes:[],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods:{
    handleSuccess(response, file, fileList){
      this.addForm.icon = response.object;
    },
    //文件删除
    handleRemove(file, fileList) {
      let filePath =file.response.object;

      this.$http.delete("/fastDfs/delete?path="+filePath)
          .then(res=>{
            if(res.data.success){
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
              this.addForm.icon = null;
            }else{
              this.$message({
                message: '删除失败!',
                type: 'error'
              });
            }
          })
    },
    //图片预览
    handlePreview(file) {
      console.log(file);
    },
    //筛选结点
    filterNode(value, data, node) {
      if (!value) return true;
      return this.findSearKey(node, value);
    },
    //递归搜索父级是否包含关键字
    findSearKey(node, key) {
      if (node.label.indexOf(key) !== -1) {
        return true;
      } else {
        if (node.parent.parent == null) {
          return false;
        } else {
          return this.findSearKey(node.parent, key);
        }
      }
    },
    // 单页大小转换
    handleSizeChange(val){
      this.query.pageSize=val;
      this.query.currentPage=1;
      this.getList(this.currentID);
    },
    handleAdd(){
      this.addForm={
        name:"",
        logo:"",
        icon:"",
        sortIndex:"",
        description:"",
        pid:""
      }
      this.addFormVisible = true;
    },
    addSubmit(){
      if(this.currentID!==null&&this.addForm.id!==0) {
        this.addForm.pid = this.currentID;
      }
      //提交
      this.$http.put("/carType",this.addForm).then(res=>{
        //{success: true, ..
        let ajaxResult = res.data;
        if(ajaxResult.success){
          this.addFormVisible = false;
          this.getTree();
          this.getList(this.currentID);
        }else{
          this.$message({
            message: ajaxResult.message,
            type: 'error'
          });
          this.getTreeData();
        }
      });
    },
    handleCurrentChange(val){
      this.query.currentPage = val;
      this.getList(this.currentID)
    },
    batchRemove(){
      let ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/carType",ids).then(() => {
          this.listLoading = false;
          this.query.currentPage=1;
          this.getTree();
          this.getList(this.currentID);
        }).catch(() => {
          this.$message({message: '网络错误!',type: 'error'});
        })
      }).catch(() => {
        this.$message({message: '已取消删除!',type: 'warning'});
      });
    },
    handleEdit(index,row){
      this.addFormVisible = true;
      this.addForm = row;
    },
    handleDel(index,row){
      this.$http.delete("/carType/"+row.id).then(()=>{
        this.getTree();
        this.getList(this.currentID);
      }).catch(()=>{
        this.$message.error("网络错误！");
      })
    },
    selsChange: function (sels){
      this.sels = sels;
    },
    getList(id){
      this.query.id = id;
      this.query.keyword = this.filters.keyword;
      this.$http.post("/carType",this.query).then(result=>{
        result = result.data;
        this.pageInfo = result.object;
      })
    },
    handleNodeClick(row){
      // this.pageInfo.rows = row.children; //每点一级只显示当前行节点儿子
      this.getList(row.id);
      this.currentID = row.id;
      this.addForm.pid = row.id; //把当前行的id作为添加表单父id
    },
    getTreeData(){
      // 发送一个异步请求: get请求 /product/carType/treeData
      this.$http.get("/carType/tree").then(res=>{
        this.currentID = 0;
        this.carTypes = res.data.object;
        this.datas = this.carTypes;  //第一次进来只展示第一级
        this.pageInfo.rows = this.carTypes;
      });
    },
    getTree(){
      // 发送一个异步请求: get请求 /product/carType/treeData
      this.$http.get("/carType/tree").then(res=>{
        this.carTypes = res.data.object;
      });
    }
  },
  mounted(){
    //对carTypes数据赋值
    this.getTreeData();
  }
};
</script>